package com.yanxin.credit.service;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;

/**
 * 自定义hasPermission判断
 */
@Service
public class CustomPermissionEvaluatorImpl implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        // 判断当前用户是否具有执行该权限的权限
        return hasPermission(authentication, permission.toString());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        // 通过目标对象的类型和ID，判断当前用户是否具有执行该权限的权限
        String target = targetType + "_" + targetId.toString();
        return hasPermission(authentication, target, permission.toString());
    }

    private boolean hasPermission(Authentication authentication, String... targets) {

        // 获取当前用户所具有的权限列表
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        // 遍历当前用户所具有的权限，判断是否有权限执行目标操作
        for (String target : targets) {
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(target)) {
                    return true;
                }
            }
        }
        return false;
    }

}
